package com.ruoyi.shop.popularize.batch.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.common.mapper.DtsSeckillBatchMapper;
import com.ruoyi.mall.common.domain.DtsSeckillBatch;
import com.ruoyi.shop.popularize.batch.service.IDtsSeckillBatchService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 秒杀商品列表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@Service
public class DtsSeckillBatchServiceImpl implements IDtsSeckillBatchService
{
    @Autowired
    private DtsSeckillBatchMapper dtsSeckillBatchMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询秒杀商品列表
     *
     * @param id 秒杀商品列表主键
     * @return 秒杀商品列表
     */
    @Override
    public DtsSeckillBatch selectDtsSeckillBatchById(Long id)
    {
        return dtsSeckillBatchMapper.selectDtsSeckillBatchById(id);
    }

    /**
     * 查询秒杀商品列表列表
     *
     * @param dtsSeckillBatch 秒杀商品列表
     * @return 秒杀商品列表
     */
    @Override
    public List<DtsSeckillBatch> selectDtsSeckillBatchList(DtsSeckillBatch dtsSeckillBatch)
    {
        return dtsSeckillBatchMapper.selectDtsSeckillBatchList(dtsSeckillBatch);
    }

    /**
     * 新增秒杀商品列表
     *
     * @param dtsSeckillBatch 秒杀商品列表
     * @return 结果
     */
    @Override
    public int insertDtsSeckillBatch(DtsSeckillBatch dtsSeckillBatch)
    {
        return dtsSeckillBatchMapper.insertDtsSeckillBatch(dtsSeckillBatch);
    }

    /**
     * 修改秒杀商品列表
     *
     * @param dtsSeckillBatch 秒杀商品列表
     * @return 结果
     */
    @Override
    public int updateDtsSeckillBatch(DtsSeckillBatch dtsSeckillBatch)
    {
        return dtsSeckillBatchMapper.updateDtsSeckillBatch(dtsSeckillBatch);
    }

    /**
     * 批量删除秒杀商品列表
     *
     * @param ids 需要删除的秒杀商品列表主键
     * @return 结果
     */
    @Override
    public int deleteDtsSeckillBatchByIds(Long[] ids)
    {
        return dtsSeckillBatchMapper.deleteDtsSeckillBatchByIds(ids);
    }

    /**
     * 删除秒杀商品列表信息
     *
     * @param id 秒杀商品列表主键
     * @return 结果
     */
    @Override
    public int deleteDtsSeckillBatchById(Long id)
    {
        return dtsSeckillBatchMapper.deleteDtsSeckillBatchById(id);
    }

    @Override
    public int updateConclude(Long id) {
        return dtsSeckillBatchMapper.updateConclude(id);
    }

    @Override
    public List<DtsSeckillBatch> selectDtsSeckillBatchBySpecId(String specId) {
        System.out.println(specId);
        return dtsSeckillBatchMapper.selectDtsSeckillBatchBySpecId(specId);
    }

    @Override
    public DtsSeckillBatch selectDtsSeckillBatchByProductId(Integer productId) {
        return dtsSeckillBatchMapper.selectDtsSeckillBatchByProductId(productId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public AjaxResult addOrUpdate(Map<String, Object> data) {
        redisTemplate.delete("seckillTime");
        redisTemplate.delete("seckillBatchList");

        List<Map<String, Object>> seckillItems = (List<Map<String, Object>>) data.get("seckillItems");
        DtsSeckillBatch dtsSeckillBatch = new DtsSeckillBatch();
        Object goodsId=data.get("goodsId");
        Object SeckillBatch=data.get("seckillBatch");
        Object total= data.get("total");
        Object RemainingQuantity=data.get("RemainingQuantity");
        Object starttime=data.get("starttime");
        Object ClosingTime=data.get("ClosingTime");
        Object seckill=data.get("seckill");

        for (Map<String, Object> item : seckillItems) {
            Integer productId = (Integer) item.get("productId");
            DtsSeckillBatch existingBatch = dtsSeckillBatchMapper.selectDtsSeckillBatchByProductId(productId);

            if (existingBatch != null) {
                // 处理价格（同之前逻辑）
                Object flashSalePriceObj = item.get("flashSalePrice");
                if (flashSalePriceObj instanceof Integer) {
                    double flashSalePrice = ((Integer) flashSalePriceObj).doubleValue();
                    existingBatch.setFlashSalePrice(flashSalePrice);
                } else if (flashSalePriceObj instanceof Double) {
                    existingBatch.setFlashSalePrice((Double) flashSalePriceObj);
                }
                // ✅ 修改：从 Integer 转换为 Long（安全转换）
                existingBatch.setSeckillBatch(String.valueOf(SeckillBatch));
                //计算商品剩余的数量
                Long shengyushulaing = Long.valueOf((Integer) item.get("remainingQuantity"))-existingBatch.getTotal()+existingBatch.getRemainingQuantity();
                existingBatch.setRemainingQuantity(shengyushulaing);
                existingBatch.setTotal(Long.valueOf((Integer) item.get("remainingQuantity")));
                existingBatch.setStarttime(String.valueOf(starttime));
                existingBatch.setClosingTime(String.valueOf(ClosingTime));
                existingBatch.setSeckill(((Integer) seckill).longValue());
                existingBatch.setFlashSalePrice(Double.parseDouble(item.get("flashSalePrice").toString()));
                dtsSeckillBatchMapper.updateDtsSeckillBatch(existingBatch);
            } else {
                DtsSeckillBatch newBatch = new DtsSeckillBatch();
                // ✅ 修改：pro2000duct_id 从 Integer 转换为 Long（若实体类字段为 Long）
                newBatch.setProduct_id(productId.longValue()); // 若实体类字段是 Long

                // 处理价格（同之前逻辑）
//                Object flashSalePriceObj = item.get("flashSalePrice");
//                if (flashSalePriceObj instanceof Integer) {
//                    double flashSalePrice = ((Integer) flashSalePriceObj).doubleValue();
//                    newBatch.setFlashSalePrice(flashSalePrice);
//                } else if (flashSalePriceObj instanceof Double) {
//                    newBatch.setFlashSalePrice((Double) flashSalePriceObj);
//                }
                // ✅ 修改：从 Integer 转换为 Long（安全转换）
                if (RemainingQuantity instanceof Integer) {
                    newBatch.setRemainingQuantity(((Integer) RemainingQuantity).longValue());
                }

                if (goodsId instanceof Number) {
                    newBatch.setGoodsId(((Number) goodsId).longValue());
                }
                newBatch.setSeckillBatch(String.valueOf(SeckillBatch));
                newBatch.setTotal(Long.valueOf((Integer) item.get("remainingQuantity")));
                newBatch.setRemainingQuantity(Long.valueOf((Integer) item.get("remainingQuantity")));
                newBatch.setConclude(0l);
                newBatch.setStarttime(String.valueOf(starttime));
                newBatch.setClosingTime(String.valueOf(ClosingTime));
                newBatch.setDelete(0);
                newBatch.setSeckill(((Integer) seckill).longValue());
                newBatch.setFlashSalePrice(Double.parseDouble(item.get("flashSalePrice").toString()));
                dtsSeckillBatchMapper.insertDtsSeckillBatch(newBatch);
            }
        }
        return AjaxResult.success("操作成功");
    }
}
